package com.rybbaby.tss.front.tssPackagePostpone.controller;

import com.google.common.collect.ImmutableMap;
import com.rybbaby.tss.core.annotation.RequestLog;
import com.rybbaby.tss.core.annotation.Token;
import com.rybbaby.tss.core.annotation.validator.RegexpValidator;
import com.rybbaby.tss.core.annotation.validator.StringValidator;
import com.rybbaby.tss.core.bean.PageBean;
import com.rybbaby.tss.core.hqlsearch.HqlGenerateUtil;
import com.rybbaby.tss.core.utils.*;
import com.rybbaby.tss.core.web.controller.BaseController;
import com.rybbaby.tss.front.tssMemberPackage.entity.TssMemberPackage;
import com.rybbaby.tss.front.tssMemberPackage.service.ITssMemberPackageService;
import com.rybbaby.tss.front.tssPackagePostpone.entity.TssPackagePostpone;
import com.rybbaby.tss.front.tssPackagePostpone.entity.ViewTssPackagePostpone;
import com.rybbaby.tss.front.tssPackagePostpone.service.ITssPackagePostponeService;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 雷春琼
 * @description 课时包延期表管理
 * @createDate 2017-08-25 下午5:12:18
 */
@Controller
@RequestMapping(value = "tssPackagePostponeController")
public class TssPackagePostponeController extends BaseController {

    @Autowired
    private ITssPackagePostponeService tssPackagePostponeService;
    @Autowired
    private ITssMemberPackageService tssMemberPackageService;

    /**
     * 获取课时包延期表列表
     *
     * @return
     * @throws IOException
     */
    @RequestLog(content = "获取课时包延期表列表", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "tssPackagePostponeList", method = RequestMethod.POST)
    public ModelAndView tssPackagePostponeList(ViewTssPackagePostpone entity, PageBean paramPageBean, @RequestParam(required = true) String targetdataId, @RequestParam(required = true) Integer type) {
        ModelAndView mav = null;
        try {
            Map<String, String[]> unLockMap = getParameterMap(request);
            DetachedCriteria dc = DetachedCriteria.forClass(ViewTssPackagePostpone.class);
            HqlGenerateUtil.fillDetachedCriteria(dc, entity, unLockMap);
            //dc.add(Restrictions.eq("memberId",targetdataId));
            if (type == 1) {
                //亲子会员列表
                mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssPackagePostponeListView"));
            } else if (type == 2) {
                //过渡会员列表
                mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssTransitPackagePostponeListView"));
            }
            PageBean pageBean = tssPackagePostponeService.pageList(dc, paramPageBean.getPageNo(), paramPageBean.getPageSize());
            mav.addObject(super.SEARCH_MAP, unLockMap);
            mav.addObject(super.PAGE_BEAN, pageBean);
            mav.addObject("searchFormId", SEARCH_FORM);
            mav.addObject("actionUrl", request.getRequestURI());
            mav.addObject("pagingBar", pageBean.getPagingBar(SEARCH_FORM));
            mav.addObject("serializeNum", SequenceUtil.getUpperCaseUUID());
            String requestURI = StringUtils.substringBeforeLast(request.getRequestURI(), "/");
            mav.addObject("editUrl", requestURI + "/toEditView.do");
            mav.addObject("deleteUrl", requestURI + "/delete.do");
            mav.addObject("batchDeleteUrl", requestURI + "/batchDelete.do");
        } catch (Exception e) {
            throw e;
        }
        return mav;
    }

    /**
     * 根据会员id获取获取课时包延期表信息
     *
     * @return
     * @throws IOException
     */
    @RequestLog(content = "根据会员id获取获取课时包延期表信息", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "tssPackagePostponeListByMemberId", method = RequestMethod.POST)
    public ModelAndView tssPackagePostponeListByMemberId(@RequestParam(required = true) String targetdataId, @RequestParam(required = true) String memberPackageId, @RequestParam(required = true) Integer type) {
        ModelAndView mav = null;
        try {
            if (type == 1) {
                //亲子会员获取会员课时包延期信息
                mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssPackagePostponeListView"));
            } else if (type == 2) {
                //过渡会员获取会员课时包延期信息
                mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssTransitPackagePostponeListView"));
            }
            List<Map<String, Object>> mapList = this.tssPackagePostponeService.tssPackagePostponeListByMemberId(targetdataId, memberPackageId);
            mav.addObject("mapList", mapList);
            mav.addObject("serializeNum", SequenceUtil.getUpperCaseUUID());
            String requestURI = StringUtils.substringBeforeLast(request.getRequestURI(), "/");
            mav.addObject("editUrl", requestURI + "/toEditView.do");
        } catch (Exception e) {
            throw e;
        }
        return mav;
    }


    /**
     * 转到编辑视图
     *
     * @param entity       接收编辑参数的临时对象
     * @param serializeNum 请求标识
     * @return
     */
    @RequestLog(content = "转到课时包延期表视图", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "toEditView", method = RequestMethod.GET)
    public ModelAndView toEditView(TssPackagePostpone entity, @RequestParam(required = true) String serializeNum, @RequestParam(required = true) String tartgetdateId, @RequestParam(required = true) Integer type, @RequestParam(required = false, defaultValue = "0") Integer postponeCount) {
        ModelAndView mav = null;
        if (type == 1) {
            //亲子课时包新增延期
            mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssPackagePostponeEditView"));
        } else if (type == 2) {
            //过渡课时包新增延期
            mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssTransitPackagePostponeEditView"));
        }
        mav.addObject("postponeCount", postponeCount);
        mav.addObject("serializeNum", serializeNum);
        mav.addObject("memberPackageId", tartgetdateId);
        mav.addObject("saveUrl", StringUtils.substringBeforeLast(request.getRequestURI(), "/") + "/saveOrUpdate.do");
        return mav;
    }

    /**
     * 保存编辑的对象
     *
     * @param entity 被编辑对象
     * @return
     */
    @ResponseBody
    @RequestLog(content = "保存课时包延期表对象", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "saveOrUpdate", method = RequestMethod.POST)
    public String saveOrUpdate(TssPackagePostpone entity) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            String id = entity.getId();
            ajr.setResMsg("保存成功!");
            if (StringUtils.isNotBlank(id)) {
                TssPackagePostpone destEntity = this.tssPackagePostponeService.get(id);
                BeanUtils.copyProperties(entity, destEntity, "createTime");
                this.tssPackagePostponeService.updateEntitiy(destEntity);
            } else {
                entity.setCreateTime(new java.sql.Timestamp(System.currentTimeMillis()));
                Serializable newId = this.tssPackagePostponeService.save(entity);
                //修改会员课时包延期天数
                TssMemberPackage memberPackage = this.tssMemberPackageService.get(entity.getMemberPackageId());
                int surplusValidDate = entity.getDays() + memberPackage.getSurplusValidDate();
                Date dueTime = memberPackage.getDueTime();
                Calendar cal = Calendar.getInstance();
                if (dueTime == null) {
                    dueTime = new Date();
                    cal.setTime(dueTime);
                    cal.add(Calendar.DATE,surplusValidDate);
                }else {
                    cal.setTime(dueTime);
                    cal.add(Calendar.DATE, entity.getDays());
                }
                dueTime = cal.getTime();
                String endTime = DateUtil.format(dueTime, "yyyy-MM-dd");
                Integer row = tssMemberPackageService.updateParameterById(ImmutableMap.of("surplusValidDate", surplusValidDate, "dueTime", endTime), entity.getMemberPackageId());
                if (newId == null && row > 0) {
                    ajr.setResCode(301);
                    ajr.setResMsg("保存失败!");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("保存失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }

    /**
     * 删除指定id的对象
     *
     * @param id 需要被删除的对象id
     * @return
     */
    @ResponseBody
    @RequestLog(content = "删除属性", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "delete", method = RequestMethod.GET)
    public String delete(@StringValidator(nullable = false) String id) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            ajr.setResMsg("删除成功!");
            if (StringUtils.isNotBlank(id)) {
                this.tssPackagePostponeService.deleteEntityById(id);
            } else {
                ajr.setResMsg("删除失败!");
                ajr.setResCode(302);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("删除失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }

    /**
     * 批量删除指定id的对象
     *
     * @param ids 需要被删除的对象id组成的字符串
     * @return
     */
    @ResponseBody
    @RequestLog(content = "删除属性", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "batchDelete", method = RequestMethod.GET)
    public String batchDelete(@RegexpValidator(nullable = false, regexp = "^(\\w+,?)+\\w+$") String ids) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            ajr.setResMsg("删除成功!");
            if (StringUtils.isNotBlank(ids)) {
                boolean batchDelete = this.tssPackagePostponeService.batchDelete(ids.split(","));
                if (!batchDelete) {
                    ajr.setResMsg("删除失败!");
                    ajr.setResCode(302);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("删除失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }
}
